<template>
  <page-wrap back dark hide-tab title="新建企业" stayStill>
    <view class="create">
      <u-form :model="cInfo"  ref="uForm" label-position="top">
        <u-form-item label="公司全称" prop="cname"><u-input v-model="cInfo.cname"  placeholder="请输入公司全称" /></u-form-item>
        <u-form-item label="公司简称" prop="cname_jc"><u-input v-model="cInfo.cname_jc" placeholder="请输入公司简称"  /></u-form-item>
        <u-form-item label="公司所属行业" right-icon="arrow-down-fill"  prop="tradename">
          <u-input v-model="cInfo.tradename" placeholder="请选择公司所属行业" disabled @click="handleTradeClick(item)" />
        </u-form-item>
        <u-form-item :label="item.label" right-icon="arrow-down-fill" v-for="item in selectList" :key="item.prop" :prop="item.propName || item.prop">
          <u-input v-model="cInfo[item.propName || item.prop]" :placeholder="item.placeholder" disabled @click="handleClick(item)" />
          <u-select
            v-model="item.show" 
            :mode="item.mode || 'single-column'" 
            :list="item.list" 
            :value-name="item.valueName || 'value'" 
            :label-name="item.labelName ||'label'" 
            @confirm="confirm($event, item.props)">
            </u-select>
        </u-form-item>
        <u-form-item label="营业执照">
          <view class="upload">
            <u-upload ref="uUpload"
              :max-size="2 * 1024 * 1024"
              max-count="1" 
              :action="uploadAction"
              upload-text="上传图片"
              :custom-btn="true"
              class="u-m-b-24">
                <view slot="addBtn" class="slot-btn" hover-class="slot-btn__hover" hover-stay-time="150">
                  <image :src="uploadImg" mode="" class="upload-img" />
                  <view>上传图片</view>
                </view>
              </u-upload>
              <view class="tips">*提示：需上传营业执照，不超过2M</view>
          </view>
        </u-form-item>

      </u-form>

      <view class="bottom">
        <view class="btn btn-primary btn-join" @click="submit"> 确认创建 </view>
        <view class="tips" @click="handleCall('400-884-1001')">
          <text>客服热线：<text class="tel">400-884-1001</text>（8:00-18:00）</text>
        </view>
      </view>
    </view>
      <u-popup v-model="showTrade" mode="bottom" safe-area-inset-bottom>
      <view class="u-flex u-row-between btn-group">
        <text class="cancel" @click="showTrade = false">取消</text>
        <text
          class="confirm"
          type="primary"
          size="medium"
          @click="showTrade = false"
          >保存</text
        >
      </view>
      <scroll-view scroll-y="true" style="height: 50vh">
        <TradeDataFilter
          class="filter-comp"
          @confirm="handleConfirmTrade"
        ></TradeDataFilter>
      </scroll-view>
    </u-popup>
  </page-wrap>
</template>

<script>
import { createBusinessCard, addAudit } from '@/api/modules/company'
import { uploadAction, uploadBaseUrl, getTradeList, getRegion} from "@/api/index";
import personMixin from '../mixins/personDetail';
import { cTypeList, cScaleList } from '@/utils/data';
import { getByteLength } from "@/utils/handle"
import TradeDataFilter from '../../components/TradeDataFilter.vue';

export default {
  mixins: [personMixin],
  components: {
    TradeDataFilter,
  },
  data() {
    var validateName = (rule, value, callback) => {
      if (getByteLength(value) < 4) return false
      return true
    };
    return {
      personId: uni.getStorageSync("person-id").slice(2) || undefined,
      info: '',
      uploadAction,
      uploadBaseUrl,
      uploadImg: this.$imgBase + 'company/upload.png',
      cInfo: {
        cname: '',
        cname_jc: '',
        classid: '',
        region: '',
        cxz: '',
        yuangong: '',
        tradeid: '',
        tradename: '',
        totalid: '',
      },
      classidShow: false,
      regionShow: false,
      cxzShow: false,
      yuangongShow: false,
      imgList: [],
      classArr: [],
      regionList: [],
      cTypeList: cTypeList,
      cScaleList: cScaleList,
      companyInfo: '',
      showTrade: false,
      selectList: [
        // {
        //   label: '公司行业',
        //   prop: 'classid',
        //   propName: 'tradeidName',
        //   props: ['classid','tradeidName'],
        //   valueName: 'classid',
        //   labelName: 'className',
        //   list: [],
        //   show: false,
        //   placeholder: '请选择公司行业',
        // },
        {
          label: '公司地区',
          prop: 'region',
          propName: 'regionName',
          props: ['region','regionName'],
          list: [],
          mode: 'mutil-column-auto',
          show: false,
          placeholder: '请选择公司地区',
        },
        {
          label: '公司性质',
          prop: 'cxz',
          propName: 'cxz',
          props: 'cxz',
          list: cTypeList,
          show: false,
          placeholder: '请选择公司性质',
        },
        {
          label: '公司规模',
          prop: 'yuangong',
          propName: 'yuangong',
          props: 'yuangong',
          list: cScaleList,
          show: false,
          placeholder: '请选择公司规模',
        }
      ],
      rules: {
				cname: [
					{ required: true, validator: validateName, message: '至少输入2个汉字/4个字母', trigger: ['change'],	}
				],
        cname_jc: [
					{ required: true, message: '请输入公司简称', trigger: ['change'],	}
				],
        tradeidName: [
					{ required: true, message: '请选择公司行业', trigger: ['change'],	}
        ],
        regionName: [
					{ required: true, message: '请选择公司地区', trigger: ['change'],	}
        ],
        cxz: [
					{ required: true, message: '请选择公司性质', trigger: ['change'],	}
        ],
        yuangong: [
					{ required: true, message: '请选择公司规模', trigger: ['change'],	}
        ],
        tradename: [
					{ required: true, message: '请选择公司所属行业', trigger: ['change'],	}
        ]
			}
    }
  },
  onReady() {
		this.$refs.uForm.setRules(this.rules);
	},
  created() {
    this.info = uni.getStorageSync('recCardInfo')
    this.cInfo.cname = this.info.cname;
    this.getPersonDetail(); // from personMixin
    // this.getTradeList();
    this.getRegion();
  },

  methods: {
    // getTradeList() {
    //   let params = {
    //     tradeid: this.$tradeId,
    //   }
    //   getTradeList(params).then(res => {
    //     this.classArr = res.data;
    //     this.selectList[0].list = this.classArr;
    //   })
    // },
    getRegion() {
      getRegion({}).then(res => {
        this.regionList = this.formatRegionData(res.data);
        this.regionList.shift();
        this.regionList.pop();
        this.selectList[0].list = this.regionList;
      })
    },
    formatRegionData(data) {
      if(data) {
        let list = [];
        for(let k in data) {
          let obj = {
            label: data[k].name,
            value: k,
          }
          if(data[k].children) {
            obj.children = this.getChildrenData(data[k].children)
          }
          list.push(obj)
        }
        return list;
      }
      return [];
    },
    getChildrenData(data) {
      if(data) {
        let list = [];
        for(let k in data) {
          let obj = {
            label: data[k],
            value: k,
          }
          if(data[k].children) {
            obj.children = this.getChildrenData(data[k].children)
          }
          list.push(obj)
        }
        return list;
      }
      return [];
    },
    handleClick(item) {
      item.show = true;
    },
    submit() {
      this.$refs.uForm.validate(valid => {
				if (valid) {
          this.handleCheckUpload();
				} else {
					console.log('验证失败');
				}
			});
    },
    handleCheckUpload() {
      let files = [];
      files = this.$refs.uUpload.lists.filter(val => {
        return val.progress == 100;
      })
      // 如果您不需要进行太多的处理，直接如下即可
      // files = this.$refs.uUpload.lists;
      this.imgList = []
      files.forEach(ele => {
        this.imgList.push(uploadBaseUrl + ele.response)
      })

      if(this.imgList.length) {
        this.createBusinessCard();
      } else {
        uni.showToast({
          title: "请上传营业执照",
          icon: 'none'
        })
      }
    },
    // 创建
    createBusinessCard() {
      // let params = {
      //   person_id: this.personId,
      //   company_id: '',
      //   personArr: JSON.stringify({
      //     pic: this.info.avatar,
      //     iname: this.info.name,
      //     mobile: this.userInfo.shouji, // from personMixin
      //     pnames: this.info.pnames,
      //     email: this.info.email,
      //   }),
      //   companyArr: JSON.stringify({
      //     cname: this.cInfo.cname,
      //     cname_jc: this.cInfo.cname_jc,
      //     logopath: '',
      //     lxr_trade: this.cInfo.classid,
      //     work_area: this.cInfo.region,
      //     cxz: this.cInfo.cxz,
      //     yuangong: this.cInfo.yuangong,
      //     totalid: 0,
      //     tradeid: this.$tradeId,
      //     my_url: '',
      //     homename: '',
      //   }),
      //   conditionArr: JSON.stringify({
      //     source: 'mp'
      //   }),
      // }
      let params = {
        personId: this.personId,
        companyId: '',
        personArr: JSON.stringify({
          pic: this.info.avatar,
          iname: this.info.name,
          mobile: this.userInfo.shouji, // from personMixin
          pnames: this.info.pnames,
          email: this.info.email,
        }),
        companyArr: JSON.stringify({
          cname: this.cInfo.cname,
          cnameJc: this.cInfo.cname_jc,
          logopath: '',
          lxrTrade: this.cInfo.classid,
          workArea: this.cInfo.region,
          cxz: this.cInfo.cxz,
          yuangong: this.cInfo.yuangong,
          totalid: this.cInfo.totalid,
          tradeid: this.cInfo.tradeid,
          myUrl: '',
          homename: '',
        })
      }
      uni.showLoading({
        title: '',
        mask: true,
      });
      createBusinessCard(params).then(res => {
        if(res && res.code == 200) {
          this.companyInfo = res.data.company_info;
          uni.setStorageSync("company-id", this.companyInfo.id);
          this.addAudit()
        } else {
          uni.showToast({
            title: res.status_desc,
            icon: 'none'
          })
        }
      }).catch(err => {
        uni.hideLoading()
        uni.showToast({
          title: err,
          icon: 'none'
        })
      })
    },

    // 营业执照认证
    addAudit() {
      let img = this.imgList[0];
      let params = {
        company_id: this.companyInfo.id,
        person_id: this.personId,
        regInfoArr: JSON.stringify({
          cname: this.companyInfo.cname,
          iname: this.userInfo.iname,
          pname: this.userInfo.iname,
          idcard: ' ', // 暂无个人认证
          pavatar: this.userInfo.pic || ' ',
          resume_receiv_email: this.userInfo.email,
          mobile: this.userInfo.shouji, // from personMixin
          apply_data: img,
          apply_data_type: 1, //认证类型：1.营业执照 2 在职证明 3 工牌 4 名片
        })
      };
      uni.showLoading({
        title: '',
        mask: true,
      });
      addAudit(params).then(res => {
        uni.hideLoading();
        if(res && res.code == 200) {
          // uni.removeStorageSync('recCardInfo');
          // uni.showToast({
          //   title: res.status_desc || '提交成功',
          //   icon: 'none'
          // });
          setTimeout(() => {
            uni.reLaunch({
              url: '/pagesSub/company/selectCert/index',
            });
          }, 1000);
        } else {
          uni.hideLoading();
          uni.showToast({
            title: res.status_desc || '提交失败',
            icon: 'none'
          })
        }
      }).catch(err => {
        uni.hideLoading();
      })
    },
    // 拨打电话
    handleCall(mobile) {
      uni.makePhoneCall({
        phoneNumber: mobile,
      });
    },
    confirm(e, prop) {
      if(Array.isArray(prop)) {
        if(e.length == 1) {
          this.cInfo[prop[0]] = e[0].value;
          this.cInfo[prop[1]] = e[0].label;
        } else {
          this.cInfo[prop[0]] = e[e.length-1].value;
          this.cInfo[prop[1]] = e.map(item=> item.label).join('-');
        }
        
      } else {
        this.cInfo[prop] = e[0].value
      }
    },
    handleTradeClick(){
      this.showTrade = true
    },
    handleConfirmTrade(item) {
      this.cInfo.tradeid = item.tradeid;
      this.cInfo.tradename = item.tradename;
      this.cInfo.totalid = item.totalid;
      this.showTrade = false;
    },
  },
}
</script>

<style lang="scss" scoped>
.create {
  flex: 1;
  padding: $uni-spacing-col-big;
  background-color: $uni-bg-color;
  padding-bottom: calc(240rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(240rpx + env(safe-area-inset-bottom));
  .cinfo {
    margin-bottom: $uni-spacing-col-big;
    &-name {
      font-weight: bold;
      color: #000;
    }
  }
  .upload {
    color: $uni-text-color-333;
    .slot-btn {
      margin: 10rpx;
      height: 140rpx;
      padding: 20rpx;
      line-height: 1;
      font-size: 24rpx;
      color: #666;
      border: 2rpx dashed #666;
      border-radius: $uni-border-radius-lg;
      text-align: center;
    }
    .upload-img {
      display: inline-block;
      margin-bottom: 10rpx;
      width: 44rpx;
      height: 44rpx;
    }
    .tips {
      font-size: $uni-font-size-sm;
      color: $uni-text-color-999;
    }
  }
  .bottom {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 10;
    background-color: $uni-bg-color;
    padding: 32rpx;
    padding-bottom: calc(32rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(32rpx + env(safe-area-inset-bottom));
    .btn {
      width: 100%;
      margin-bottom: 40rpx;
    }
    .tips {
      text-align: center;
      font-size: $uni-font-size-sm;
      color: $uni-text-color-999;
      .tel {
        color: #f75a3e;
      }
    }
  }
}

.btn-group {
  padding: 0 24rpx;
  line-height: 102rpx;
  .cancel,
  .confirm {
    padding: 0 16rpx;
  }
}
</style>